import random

from django.http import HttpResponse, request
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from meiduo_mall.libs.captcha.captcha import captcha


# Create your views here.
from django_redis import get_redis_connection
from rest_framework.views import APIView
import logging
from meiduo_mall.utils.yuntongxun.sms import CCP
from verifications.serializer import ImageCodeCheckSerializer
from . import constants
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')


class ImageCodeView(APIView):
    # 图片验证码
    def get(self,request,image_code_id):
        # 接收参数
        # 校验参数


        # 生成验证码图片

        text,image = captcha.generate_captcha()
        # 保存真实值
        # TODO get_redis_connection()是获取连接redis连接对象的方法，参数为获取的是哪个redis连接配置项
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex("image_%s" % image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        # 返回图片
        return HttpResponse(image,content_type='image/jpg')



    # TODO 获取手机验证码 视图函数
class SMSCodeView(GenericAPIView):
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):

        # 定义检验参数由序列化器检验
        serializer = self.get_serializer(data = request.query_params)
        serializer.is_valid(raise_exception = True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0,999999)
        print("生成%s" % sms_code)

        # 保存信息验证码
        redis_conn = get_redis_connection('verify_codes')

        # 建立redis管道
        # pl = redis_conn.pipeline()
        # pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        #
        # # 随便创建了一个 mobile 的redis ，存储的时间为一分钟
        # pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)


        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        # 发送短信验证码

        # ccp = CCP()
        # expires = constants.IMAGE_CODE_REDIS_EXPIRES // 60
        # ccp.send_template_sms(mobile,[sms_code,expires],constants.SMS_CODE_TEMP_ID)
        # 
        #   TODO   异步发送手机验证码
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile, sms_code,expires, constants.SMS_CODE_TEMP_ID)
        
        return Response({"message": "OK"})




